/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.infor.web;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.google.gson.Gson;
import com.jeeplus.core.mapper.JsonMapper;
import com.jeeplus.modules.infor.entity.LnCustomersImport;
import com.jeeplus.modules.infor.entity.ReAddress;
import com.jeeplus.modules.infor.mapper.ReAddressMapper;
import com.jeeplus.modules.infor.service.ProjectService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.wms.util.CopyUtil;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.infor.entity.LnCustomers;
import com.jeeplus.modules.infor.service.LnCustomersService;

/**
 * 下游客户Controller
 * @author 李超辉
 * @version 2017-11-22
 */
@Controller
@RequestMapping(value = "${adminPath}/infor/lnCustomers")
public class LnCustomersController extends BaseController {

	@Autowired
	private LnCustomersService lnCustomersService;
	@Autowired
	private ReAddressMapper mapper;
	@Autowired
	private ProjectService projectService;
	
	@ModelAttribute
	public LnCustomers get(@RequestParam(required=false) String id) {
		LnCustomers entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = lnCustomersService.get(id);
		}
		if (entity == null){
			entity = new LnCustomers();
		}
		return entity;
	}
	
	/**
	 * 下游客户列表页面
	 */
	@RequiresPermissions("infor:lnCustomers:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/infor/lnCustomersList";
	}
	
		/**
	 * 下游客户列表数据
	 */
	@ResponseBody
	@RequiresPermissions("infor:lnCustomers:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(LnCustomers lnCustomers, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){lnCustomers.setProject(projectService.findUniqueByProperty("name",pro));}
		Page<LnCustomers> page = lnCustomersService.findPage(new Page<LnCustomers>(request, response), lnCustomers);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑下游客户表单页面
	 */
	@RequiresPermissions(value={"infor:lnCustomers:view","infor:lnCustomers:add","infor:lnCustomers:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(LnCustomers lnCustomers, Model model) {
		if(lnCustomers.getIsNewRecord()){
			String pro= UserUtils.getUseroffice();
			if(!pro.equals("总部")){lnCustomers.setProject(projectService.findUniqueByProperty("name",pro));}
		}
		model.addAttribute("lnCustomers", lnCustomers);
		return "modules/infor/lnCustomersForm";
	}
	/**
	 * 查看，增加，编辑下游客户表单页面
	 */
	@RequiresPermissions(value={"infor:lnCustomers:view","infor:lnCustomers:add","infor:lnCustomers:edit"},logical=Logical.OR)
	@RequestMapping(value = "form1")
	public String form1(LnCustomers lnCustomers, Model model) {
		if(lnCustomers.getIsNewRecord()){
			String pro= UserUtils.getUseroffice();
			if(!pro.equals("总部")){lnCustomers.setProject(projectService.findUniqueByProperty("name",pro));}
		}
		model.addAttribute("lnCustomers", lnCustomers);
		return "modules/infor/1/lnCustomersForm";
	}
	/**
	 * 查看，增加，编辑下游客户表单页面
	 */
	@RequiresPermissions(value={"infor:lnCustomers:view","infor:lnCustomers:add","infor:lnCustomers:edit"},logical=Logical.OR)
	@RequestMapping(value = "form2")
	public String form2(LnCustomers lnCustomers, Model model) {
		if(lnCustomers.getIsNewRecord()){
			String pro= UserUtils.getUseroffice();
			if(!pro.equals("总部")){lnCustomers.setProject(projectService.findUniqueByProperty("name",pro));}
		}
		model.addAttribute("lnCustomers", lnCustomers);
		return "modules/infor/2/lnCustomersForm";
	}

	/**
	 * 保存下游客户
	 */
	@ResponseBody
	@RequiresPermissions(value={"infor:lnCustomers:add","infor:lnCustomers:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(LnCustomers lnCustomers, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, lnCustomers)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){lnCustomers.setProject(projectService.findUniqueByProperty("name",pro));}

		//新增或编辑表单保存
		lnCustomersService.save(lnCustomers);//保存
		j.setSuccess(true);
		j.setMsg("保存下游客户成功");
		return j;
	}
	
	/**
	 * 删除下游客户
	 */
	@ResponseBody
	@RequiresPermissions("infor:lnCustomers:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(LnCustomers lnCustomers, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		lnCustomersService.delete(lnCustomers);
		j.setMsg("删除下游客户成功");
		return j;
	}

	@RequestMapping("getLnCustomersByName")
	@ResponseBody
	public  String getLnCustomersByName(String name,String pro){
		ReAddress r=new ReAddress();
		r.setAddress(name);
		r.setProjectName(UserUtils.getUseroffice());
		List<ReAddress> list=mapper.findList(r);
//		LnCustomers lnCustomers=new LnCustomers();
//		lnCustomers.setName(name);
//		lnCustomers.setProject(projectService.findUniqueByProperty("name",pro));
//		List<LnCustomers> list=lnCustomersService.findList(lnCustomers);
		Gson gson=new Gson();
		return gson.toJson(list).toString();
	}
	/**
	 * 批量删除下游客户
	 */
	@ResponseBody
	@RequiresPermissions("infor:lnCustomers:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			lnCustomersService.delete(lnCustomersService.get(id));
		}
		j.setMsg("删除下游客户成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("infor:lnCustomers:export")
    @RequestMapping(value = "export")
    public String exportFile(LnCustomers lnCustomers, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "下游客户"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
			String pro=(UserUtils.getUseroffice());
			if(pro!="总部"){
				lnCustomers.setProject(projectService.findUniqueByProperty("name",pro));}
            Page<LnCustomers> page = lnCustomersService.findPage(new Page<LnCustomers>(request, response, -1), lnCustomers);
			List<LnCustomers> ln=page.getList();
			List<LnCustomersImport> list=new ArrayList<LnCustomersImport>();
			for(LnCustomers l:ln){
             l=lnCustomersService.get(l.getId());
             ReAddress r=l.getReAddressList().get(0);
				LnCustomersImport lnc=new LnCustomersImport();
				lnc.setProject(l.getProject());
				lnc.setAddress(l.getAddress());
				lnc.setName(l.getName());
				lnc.setCompany(l.getCompany());
				lnc.setPerson(l.getPerson());
				lnc.setType(l.getRemarks());
				lnc.setPhone(l.getPhone());
				lnc.setAddress1(r.getAddress());
				lnc.setProvince(r.getProvince());
				lnc.setCity(r.getCity());
				lnc.setArrive(r.getArrive());
				lnc.setLine(r.getLine());
				lnc.setFreight(r.getFreight());
				lnc.setMileage(r.getMileage());
				lnc.setNeeds(r.getNeeds());
				lnc.setPhone1(r.getPhone());
				lnc.setPerson1(r.getPerson());
				list.add(lnc);

			}
    		new ExportExcel("下游客户", LnCustomersImport.class).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出下游客户失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/infor/lnCustomers/list?repage";
    }
    
    @ResponseBody
    @RequestMapping(value = "det")
	public ReAddress detail(String i) {
		ReAddress r=mapper.get(i);
		return  r;
	}

	@ResponseBody
	@RequestMapping(value = "childdet")
	public ReAddress childdet(String i) {

		return  mapper.get(i);
	}
	

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("infor:lnCustomers:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<LnCustomersImport> list = ei.getDataList(LnCustomersImport.class);
			for (LnCustomersImport l : list){
				try{
					String pro=UserUtils.getUseroffice();
					if(!pro.equals("总部")){
						l.setProject(projectService.findUniqueByProperty("name",pro));
					}
					LnCustomers lnCustomers=new LnCustomers();
					lnCustomers= (LnCustomers) CopyUtil.Copy(lnCustomers,l,false);
					lnCustomers.setRemarks(l.getType());
					lnCustomersService.save(lnCustomers);
					ReAddress r=new ReAddress();
					r= (ReAddress) CopyUtil.Copy(r,l,false);
					r.setAddress(l.getAddress1());
					r.setPhone(l.getPhone1());
					r.setPerson(l.getPerson1());
					r.setArrive(l.getArrive());
					r.setLnCustomers(lnCustomers);
					r.setProjectName(UserUtils.getUseroffice());
					r.setId(UUID.randomUUID().toString().replace("-",""));
					mapper.insert(r);

					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条下游客户记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条下游客户记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入下游客户失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/infor/lnCustomers/?repage";
    }
	
	/**
	 * 下载导入下游客户数据模板
	 */
	@RequiresPermissions("infor:lnCustomers:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "下游客户数据导入模板.xlsx";
    		List<LnCustomers> list = Lists.newArrayList(); 
    		new ExportExcel("下游客户数据", LnCustomersImport.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/infor/lnCustomers/?repage";
    }
	

}